function [output] = segmentation(Image)
imshow(Image);
G = fspecial('disk',10);
Ifilt = imfilter(Image,G,'replicate');
imshow(Ifilt);
labeled = kmeansColor(Ifilt,5,'rgb');
imshow(labeled, []);
segmented_images = cell(1,6);

count = 0;
for k = 1:6
    color = labeled;
    color(labeled ~= k) = 0;
    segmented_images{k} = color;
    segmented_images{k} = imclearborder(segmented_images{k});
    if sum(segmented_images{k}(:)) > 0
        count = count+1;
    end
end

mask = segmented_images{1}|segmented_images{2}|segmented_images{3}|segmented_images{4}|segmented_images{5}|segmented_images{6};
if count < 3
    labeled = kmeansColor(Ifilt,3,'rgb');
    disp('redo k means');
    [m n] = size(labeled);
    corners = [labeled(1,1), labeled(1,n), labeled(m,1), labeled(m,n)];
    mo1 = mode(corners); corners(corners==mo1) = []; mo2 = mode(corners);
    %bg = labeled(1,1); bg2 = labeled(m,n);
    if ~isnan(mo2)
        mask = labeled~=mo1 & labeled~=mo2;
    else
        mask = labeled~=mo1;
    end
    mask = imfill(mask,'holes');
    output(:,:,1) = mask;
else
    mask = medfilt2(mask,[6 6]);
    se = strel('disk',4);
    mask = imfill(mask,'holes');
    mask = imdilate(mask, se);
    mask = imfill(mask,'holes');
    mask = imerode(mask, se);

    cc = bwconncomp(mask);

    [row col] = size(mask);

    s = regionprops(cc,'Area');
    area = cat(1, s.Area);

    keep = area/(size(mask,1)*size(mask,2)) > 0.0001;
    newNumObjects = sum(keep);

    for i=1:cc.NumObjects
        if ~keep(i)
            mask(cc.PixelIdxList{i}) = 0;
        end
    end

    output = zeros(row, col, newNumObjects);
    output = logical(output);

    if newNumObjects > 1
        for i = 1:cc.NumObjects
            if keep(i)
                label = zeros(size(mask));
                label(cc.PixelIdxList{i}) = 1;
                output(:,:,i) = label;
            end
        end
    else
        output(:,:,1) = mask;
    end
end